package com.lzx.makeFriend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzx.common.utils.R;
import com.lzx.makeFriend.entity.Chat;
import com.lzx.makeFriend.entity.vo.NicknameVO;
import com.lzx.makeFriend.entity.vo.OssVO;
import com.lzx.makeFriend.mapper.ChatMapper;
import com.lzx.makeFriend.service.ChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-11-07
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {
    @Resource
    private ChatMapper chatMapper;

    //朋友聊天
    @Override
    public R friendChat(Chat chat) {
        chat.setCreateTime(new Date());
        chatMapper.insert(chat);
        return R.ok().message("发送成功");
    }

    //获取当前用户的好友聊天内容
    @Override
    public R getUserFriendChatContent(Long userId, Long friendId) {
        QueryWrapper<Chat> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("friend_id", friendId).or().eq("user_id", friendId).eq("friend_id", userId);
        List<Chat> list = chatMapper.selectList(wrapper);
        return R.ok().data("list", list);
    }

    //修改用户头像(好友聊天)
    @Transactional
    @Override
    public String updateAvatarToChat(OssVO ossVO) {
        QueryWrapper<Chat> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", ossVO.getId());
        List<Chat> chatList = chatMapper.selectList(wrapper1);
        for (Chat chat : chatList) {
            chat.setAvatar(ossVO.getAvatar());
            chatMapper.updateById(chat);
        }
        QueryWrapper<Chat> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("friend_id", ossVO.getId());
        List<Chat> chats = chatMapper.selectList(wrapper2);
        for (Chat chat : chats) {
            chat.setFriendAvatar(ossVO.getAvatar());
            chatMapper.updateById(chat);
        }
        return "修改成功";
    }

    //修改用户昵称(好友聊天)
    @Transactional
    @Override
    public String updateNicknameToChat(NicknameVO nicknameVO) {
        QueryWrapper<Chat> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", nicknameVO.getId());
        List<Chat> chatList = chatMapper.selectList(wrapper1);
        for (Chat chat : chatList) {
            chat.setNickname(nicknameVO.getNickname());
            chatMapper.updateById(chat);
        }
        QueryWrapper<Chat> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("friend_id", nicknameVO.getId());
        List<Chat> chats = chatMapper.selectList(wrapper2);
        for (Chat chat : chats) {
            chat.setFriendNickname(nicknameVO.getNickname());
            chatMapper.updateById(chat);
        }
        return "修改成功";
    }
}
